package net.posick.ws.xml;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import net.posick.tree.TraverseAction;
//import net.posick.ws.Constants;
//import android.util.Log;

public class XmlBuilder extends TraverseAction<XmlElement>
{
//    protected static final String LOG_TAG = Constants.LOG_TAG + "." + XmlBuilder.class.getSimpleName();
    
    protected StringBuilder builder;
    
    protected Map<String, Namespace> namespaces = new HashMap<String, Namespace>();

    
    public XmlBuilder(StringBuilder builder)
    {
        this.builder = builder;
    }
    
    
    @Override
    public int onNode(XmlElement node, int level)
    {
        builder.append("<").append(node.getName());
        
        Set<Namespace> namespaces = node.getNamespaces();
        if (namespaces != null && namespaces.size() > 0)
        {
            for (Namespace namespace : namespaces)
            {
                String prefix = namespace.getPrefix();
                if (!this.namespaces.containsKey(prefix))
                {
                    this.namespaces.put(prefix, namespace);
                    builder.append(" ");
                    
                    builder.append(Namespace.NAMESPACE_ATTRIBUTE_KEY);
                    if (prefix != null)
                    {
                        builder.append(":").append(prefix);
                    }
                    builder.append("=").append("\"").append(namespace.getUri()).append("\"");
//Log.i(LOG_TAG, "Setting Namespace \"" + namespace + "\" for element " + node.getName());
    
                }
            }
        }
        
        Map<Name, CharSequence> attributes = node.getAttributes();
        if (attributes != null && attributes.size() > 0)
        {
            for (Map.Entry<Name, CharSequence> entry : attributes.entrySet())
            {
                builder.append(" ").append(entry.getKey()).append("=")
                       .append("\"").append(entry.getValue()).append("\"");
            }
        }
        
        CharSequence value = node.getValue();
        if (node.hasChildren())
        {
            builder.append(">");
        } else if (value != null && value.length() > 0)
        {
            builder.append(">");
        } else
        {
            builder.append("/>");
        }
        
        return TraverseAction.CONTINUE;
    }
    
    
    @Override
    public void onCloseNode(XmlElement node, int level)
    {
        CharSequence value = node.getValue();
        if (node.hasChildren())
        {
            builder.append("</").append(node.getName()).append(">");
        } else if (value != null && value.length() > 0)
        {
            builder.append(node.getValue()).append("</").append(node.getName()).append(">");
        }
    }
}